package org.mybatis.example.batch.insert;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.mybatis.example.BlogMapper;
import org.mybatis.example.ListDivideUtil;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author zhouchaoqun
 * @date 2018/11/21 下午3:02
 */
public class MybatisSessionBatchTest {

    public static void main(String[] args) throws IOException, InterruptedException {
        String resource = "mybatis.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        List<String> list = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            list.add("name" + i);
        }

        SqlSession sqlSession = sqlSessionFactory.openSession(false);
        long start = System.currentTimeMillis();
        try {
            parallelBatchInsertWithSqlSession(list, sqlSession);
            sqlSession.commit();
            System.out.println("use time: " + (System.currentTimeMillis() - start) + "ms");
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
        } finally {
            sqlSession.close();
        }

        Thread.sleep(2000);


    }

    private static void parallelBatchInsertWithSqlSession(List<String> list, SqlSession sqlSession) {
        BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);

        List<List<String>> lists = ListDivideUtil.averageAssign(list, 10);
        List<CompletableFuture> futures = new ArrayList<>();
        for (List<String> names : lists) {
            CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> blogMapper.insertBatch(names));
            futures.add(voidCompletableFuture);
        }

        CompletableFuture.allOf(futures.toArray(new CompletableFuture[]{})).join();
    }
}
